package org.amn.concurrent;

import java.io.File;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;

import org.amn.file.FileManager;
import org.amn.file.FileStatus;
import org.amn.file.FileUtils;
import org.apache.log4j.Logger;

/**
 * <p>
 * 描述:1.将成功的文件归档到backup,
 *      2.单线程
 *      3.清理空目录文件,加入个Scanner，Backupper,Worker里面了，exception运营手工处理。
 * </p>
 *
 * @see
 * @author yangjun1120@gmail.com
 *
 */
public class Backupper implements Runnable {
    private static Logger logger = Logger.getLogger(Backupper.class);

    private boolean stop;

    private static Random r = new Random();

    private FileManager fm;

    public Backupper(FileManager fm) {
        this.fm = fm;
    }

    public boolean isStop() {
        return stop;
    }

    public void stop() {
        this.stop = true;
    }

    private void sleepRandom() {
        try {
            Thread.sleep(r.nextInt(60) * 1000);
        } catch (InterruptedException e) {
            //e.printStackTrace();
        }
    }

    @Override
    public void run() {
        //while (!stop) {
        try {
            if (logger.isInfoEnabled())
                logger.info("Backupper heartbeat.");
            backup();
        } catch (Throwable e) {
            logger.error("backupper run exception", e);
        }
        //sleepRandom();
        //}

    }

    private void backup() {
        String source = fm.getPath(FileStatus.SUCCESS);
        String dest = fm.getPath(FileStatus.BACKUP);
        File[] listDir = FileUtils.listDir(source);
        for (File f : listDir) {

            if (enableBackup(f)) {
                String absolutePath = f.getAbsolutePath();
                String reg = Matcher.quoteReplacement(source);
                String rep = Matcher.quoteReplacement(dest);
                String newPath = absolutePath.replaceAll(reg, rep);

                //rename path
                if (!FileUtils.renameTo(f, newPath)) {
                    logger.error("failure to backup file,old path:" + absolutePath + ",new path:" + newPath);
                }
            }

        }

        if (logger.isDebugEnabled()) {
            logger.debug("backupper end!");
        }
    }

    private boolean enableBackup(File d) {

        long backupTime = fm.getFileBackupTime();
        TimeUnit timeUnit = fm.getTimeUnit();
        long s = TimeUnit.MILLISECONDS.convert(backupTime, timeUnit);

        if ((System.currentTimeMillis() - d.lastModified()) >= s) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) throws Exception {

        File f = new File("D:\\11");
        f.renameTo(new File("d:\\12"));
        //System.out.println(f.listFiles().length);

    }
}
